package com.funsport.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.funsport.entity.*;
import com.funsport.mapper.EventGroupMapper;
import com.funsport.mapper.EventGroupMemberMapper;
import com.funsport.mapper.EventMapper;
import com.funsport.mapper.EventSignupMapper;
import com.funsport.mapper.UserMapper;
import com.funsport.service.IEventGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 活动分组服务实现类
 *
 * @author Fun-Sport Team
 */
@Slf4j
@Service
public class EventGroupServiceImpl extends ServiceImpl<EventGroupMapper, EventGroup> implements IEventGroupService {

    @Autowired
    private EventGroupMapper eventGroupMapper;

    @Autowired
    private EventGroupMemberMapper eventGroupMemberMapper;

    @Autowired
    private EventMapper eventMapper;

    @Autowired
    private EventSignupMapper eventSignupMapper;

    @Autowired
    private UserMapper userMapper;

    // 预定义的颜色方案（颜色名称和颜色代码）
    private static final Map<String, String> COLOR_SCHEMES = new LinkedHashMap<String, String>() {{
        put("红队", "#FF4444");
        put("蓝队", "#4444FF");
        put("绿队", "#44FF44");
        put("黄队", "#FFD700");
        put("紫队", "#9370DB");
        put("橙队", "#FF8C00");
        put("粉队", "#FF69B4");
        put("青队", "#00CED1");
        put("棕队", "#8B4513");
        put("灰队", "#808080");
    }};

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createGroupsAndAssignParticipants(Long eventId, Integer groupCount, Long creatorId) {
        try {
            // 1. 验证活动是否存在
            Event event = eventMapper.selectById(eventId);
            if (event == null) {
                log.error("活动不存在: {}", eventId);
                return false;
            }

            // 2. 验证是否是创建者
            if (!event.getCreatorId().equals(creatorId)) {
                log.error("只有创建者才能创建分组");
                return false;
            }

            // 3. 验证是否启用了分组功能
            if (event.getEnableGrouping() == null || !event.getEnableGrouping()) {
                log.error("活动未启用分组功能");
                return false;
            }

            // 4. 验证是否已经分组
            if (event.getIsGrouped() != null && event.getIsGrouped()) {
                log.error("活动已经分组，请先删除现有分组");
                return false;
            }

            // 5. 验证分组数量
            if (groupCount < 2 || groupCount > 10) {
                log.error("分组数量必须在2-10之间");
                return false;
            }

            // 6. 查询所有已确认的参与者（不包括候补和已取消的）
            QueryWrapper<EventSignup> signupWrapper = new QueryWrapper<>();
            signupWrapper.eq("event_id", eventId)
                    .eq("status", "confirmed")
                    .eq("is_waitlist", false);
            List<EventSignup> signups = eventSignupMapper.selectList(signupWrapper);

            if (signups.isEmpty()) {
                log.error("没有确认的参与者");
                return false;
            }

            // 7. 如果参与者数量少于分组数量，调整分组数量
            if (signups.size() < groupCount) {
                groupCount = signups.size();
                log.info("参与者数量少于分组数量，调整为: {}", groupCount);
            }

            // 8. 创建分组
            List<String> colorNames = new ArrayList<>(COLOR_SCHEMES.keySet());
            List<EventGroup> groups = new ArrayList<>();
            for (int i = 0; i < groupCount; i++) {
                EventGroup group = new EventGroup();
                group.setEventId(eventId);
                group.setGroupName(colorNames.get(i));
                group.setGroupColor(COLOR_SCHEMES.get(colorNames.get(i)));
                group.setGroupOrder(i + 1);
                group.setMemberCount(0);
                eventGroupMapper.insert(group);
                groups.add(group);
            }

            // 9. 自动均匀分配参与者（轮询算法）
            // 打乱参与者顺序，使分组更随机
            Collections.shuffle(signups);

            int groupIndex = 0;
            for (EventSignup signup : signups) {
                EventGroup group = groups.get(groupIndex);

                EventGroupMember member = new EventGroupMember();
                member.setGroupId(group.getId());
                member.setEventId(eventId);
                member.setUserId(signup.getUserId());
                member.setSignupId(signup.getId());
                eventGroupMemberMapper.insert(member);

                // 更新分组成员数量
                group.setMemberCount(group.getMemberCount() + 1);

                // 轮询到下一个分组
                groupIndex = (groupIndex + 1) % groupCount;
            }

            // 10. 更新所有分组的成员数量
            for (EventGroup group : groups) {
                eventGroupMapper.updateById(group);
            }

            // 11. 更新活动状态
            event.setGroupCount(groupCount);
            event.setIsGrouped(true);
            eventMapper.updateById(event);

            log.info("成功为活动 {} 创建 {} 个分组，分配 {} 名参与者", eventId, groupCount, signups.size());
            return true;

        } catch (Exception e) {
            log.error("创建分组失败: {}", e.getMessage(), e);
            throw new RuntimeException("创建分组失败: " + e.getMessage());
        }
    }

    @Override
    public List<Map<String, Object>> getEventGroupsWithMembers(Long eventId) {
        try {
            // 1. 查询所有分组
            List<EventGroup> groups = eventGroupMapper.selectByEventId(eventId);
            if (groups.isEmpty()) {
                return new ArrayList<>();
            }

            // 2. 查询所有分组成员
            List<EventGroupMember> allMembers = eventGroupMemberMapper.selectByEventId(eventId);

            // 3. 按分组ID分组成员
            Map<Long, List<EventGroupMember>> membersByGroup = allMembers.stream()
                    .collect(Collectors.groupingBy(EventGroupMember::getGroupId));

            // 4. 组装结果
            List<Map<String, Object>> result = new ArrayList<>();
            for (EventGroup group : groups) {
                Map<String, Object> groupData = new HashMap<>();
                groupData.put("id", group.getId());
                groupData.put("groupName", group.getGroupName());
                groupData.put("groupColor", group.getGroupColor());
                groupData.put("groupOrder", group.getGroupOrder());
                groupData.put("memberCount", group.getMemberCount());

                // 查询成员详细信息
                List<EventGroupMember> members = membersByGroup.getOrDefault(group.getId(), new ArrayList<>());
                List<Map<String, Object>> memberDetails = new ArrayList<>();

                for (EventGroupMember member : members) {
                    User user = userMapper.selectById(member.getUserId());
                    if (user != null) {
                        Map<String, Object> memberData = new HashMap<>();
                        memberData.put("userId", user.getId());
                        memberData.put("nickname", user.getNickname());
                        memberData.put("avatar", user.getAvatar());
                        memberData.put("signupId", member.getSignupId());
                        memberDetails.add(memberData);
                    }
                }

                groupData.put("members", memberDetails);
                result.add(groupData);
            }

            return result;

        } catch (Exception e) {
            log.error("查询分组信息失败: {}", e.getMessage(), e);
            return new ArrayList<>();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteEventGroups(Long eventId) {
        try {
            // 1. 删除所有分组成员
            QueryWrapper<EventGroupMember> memberWrapper = new QueryWrapper<>();
            memberWrapper.eq("event_id", eventId);
            eventGroupMemberMapper.delete(memberWrapper);

            // 2. 删除所有分组
            QueryWrapper<EventGroup> groupWrapper = new QueryWrapper<>();
            groupWrapper.eq("event_id", eventId);
            eventGroupMapper.delete(groupWrapper);

            // 3. 更新活动状态
            Event event = eventMapper.selectById(eventId);
            if (event != null) {
                event.setIsGrouped(false);
                event.setGroupCount(0);
                eventMapper.updateById(event);
            }

            log.info("成功删除活动 {} 的所有分组", eventId);
            return true;

        } catch (Exception e) {
            log.error("删除分组失败: {}", e.getMessage(), e);
            throw new RuntimeException("删除分组失败: " + e.getMessage());
        }
    }

    @Override
    public Map<String, Object> getUserGroupInEvent(Long eventId, Long userId) {
        try {
            // 查询用户在活动中的分组成员记录
            EventGroupMember member = eventGroupMemberMapper.selectByEventIdAndUserId(eventId, userId);
            if (member == null) {
                return null;
            }

            // 查询分组信息
            EventGroup group = eventGroupMapper.selectById(member.getGroupId());
            if (group == null) {
                return null;
            }

            // 组装结果
            Map<String, Object> result = new HashMap<>();
            result.put("groupId", group.getId());
            result.put("groupName", group.getGroupName());
            result.put("groupColor", group.getGroupColor());
            result.put("groupOrder", group.getGroupOrder());

            return result;

        } catch (Exception e) {
            log.error("查询用户分组失败: {}", e.getMessage(), e);
            return null;
        }
    }
}

